import {
	BASE_URL,
	TOKENNAME
} from '@/config.js'
import {
	uploadFile
} from '@/api/base.js'
import dayjs from 'dayjs'

const upload = (obj = {
	filePath: '',
	name: '',
	files: [],
	formData: {},
	type: 'album'
}, fn, showProgress = false) => {
	let {
		filePath,
		name,
		files,
		type,
		formData
	} = obj
	type = obj.type || 'avatar'
	formData = formData || {}
	const randomName = (fileName = '') => (type + dayjs().valueOf().toString() + parseInt(Math.random() * 10000 +
		10000) + '.' + fileName.split('.')[fileName.split('.').length - 1])
	let token = uni.getStorageSync(TOKENNAME)
	const uploadTask = uni.uploadFile({ //将本地资源上传到开发者服务器
		url: `${ BASE_URL }/upload/file?token=${ token }&type=${ type }`,
		filePath,
		name: randomName(filePath),
		headers: {
			"Content-Type": "multipart/form-data"
		},
		formData: {
			...formData
		},
		success: (res) => {
			let re = (JSON.parse(res.data))
			if (!re.code) {
				// 上传成功
				fn && typeof fn === 'function' && fn({
					progress: -1,
					status: 'complete',
					msg: (re).data.baseData[0]
				})
			} else {
				uni.showToast({
					title: re.msg,
					icon: 'none'
				})
			}
		},
		fail: (e) => {
			console.log('uploadError => ', e)
			// 上传报错
			fn && typeof fn === 'function' && fn({
				progress: -1,
				status: 'error',
				msg: e
			})
		}
	});
	//通过 uploadTask，可监听上传进度变化事件，以及取消上传任务。
	//abort : 中断上传任务
	//onProgressUpdate : 监听上传进度变化
	if (showProgress) {
		uploadTask.onProgressUpdate((res) => {
			// console.log('上传进度' + res.progress);
			// console.log('已经上传的数据长度' + res.totalBytesSent);
			// console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
			// 正在上传的文件，会将自身实例通过参数返回，允许通过回调函数进行中断上传
			fn && typeof fn === 'function' && fn(res, uploadTask)
		});
	}
}

export default upload
